package handlers

import (
	"commodity-mgr/cache"
	"commodity-mgr/models"
	"commodity-mgr/pkg"
	"encoding/json"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
)

func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "字段不能为空",
		})
		return
	}
	redis_key := "redis_log_" + username
	redis_Count, _ := cache.Rdb.Get(cache.Ctx, redis_key).Int()
	if redis_Count >= 3 {
		c.JSON(200, gin.H{
			"code": 200,
			"msg":  "登录次数大于三次，禁止登录",
		})
		return
	}
	var user models.Login
	err := models.DB.Where("username=?", username).First(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "用户不存在",
		})
		return
	}
	if user.ID == 0 {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "用户不存在",
		})
		return
	}
	if pkg.Md5(password) != user.Password {
		cache.Rdb.Incr(cache.Ctx, redis_key)
		if redis_Count == 2 {
			cache.Rdb.Set(cache.Ctx, redis_key, 3, time.Hour*2)
			c.JSON(200, gin.H{
				"code": 400,
				"msg":  "登录已上锁,禁止登录",
			})
			return
		}
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "密码错误",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "登录成功",
		"user": user,
	})
}
func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	pageSize, _ := strconv.Atoi(c.DefaultQuery("pageSize", "2"))
	offset := (page - 1) * pageSize
	title := c.Query("title")

	var arr []models.Commodity
	redis_key := "redis_list" + strconv.Itoa(page)
	redsData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if redsData == "" {
		models.DB.Offset(offset).Limit(pageSize).Where("title like?", "%"+title+"%").Find(&arr)
		jsonData, _ := json.Marshal(arr)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(redsData), &arr)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"list": arr,
	})
}
func AddCom(c *gin.Context) {
	uid, _ := strconv.Atoi(c.PostForm("uid"))
	cid, _ := strconv.Atoi(c.PostForm("cid"))
	content := c.PostForm("content")
	data := models.Comment{

		Uid:     uid,
		Cid:     cid,
		Content: content,
	}
	models.DB.Create(&data)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "发布成功",
	})

}
func AddList(c *gin.Context) {
	uid, _ := strconv.Atoi(c.PostForm("uid"))
	var arr []models.Comment
	redis_key := "redis_com" + strconv.Itoa(uid)
	redsi_data, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if redsi_data == "" {
		models.DB.Where("id=?", uid).Order("id DESC").Find(&arr)
		json_data, _ := json.Marshal(arr)
		cache.Rdb.Set(cache.Ctx, redis_key, json_data, time.Hour*2)
	} else {
		json.Unmarshal([]byte(redsi_data), &arr)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"list": arr,
	})

}
